import json
import random
from urllib import parse
from fastapi import APIRouter, status, BackgroundTasks, Request
from fastapi.responses import JSONResponse
from utils.handler_request_log import handler_request_log
from utils.mongodb_utils import MongoDBLink
from utils.redis_control.redis_operations import RedisOperator
from utils.log import log
user = parse.quote_plus("viviu")
passwd = parse.quote_plus("viu@1234")
modb_client = MongoDBLink(
    uri=f'mongodb://{user}:{passwd}@10.86.3.113:27017/?authSource=admin',
    dbname='sit_charge_mock_data', coll_name='sit_charge_mock_data')
redis_client = RedisOperator()

cgvmagent_router = APIRouter()


@cgvmagent_router.post("/{area_type}/{ip}:28668/v1/cgagent/game/startGame")
async def start_game(request: Request, area_type, ip):
    is_forward = True
    path = request.path_params
    request_method = request.method
    # 使用示例
    redis_value = redis_client.get_key("startGame")
    if redis_value:
        if redis_value.upper() == request_method:
            is_forward = False
    sit_base_url = "http://idc-202:40000" + f"/{area_type}/{ip}:28668/v1/cgagent/game/startGame"
    log.error(f"sit_base_url={sit_base_url}")
    try:
        raw_body = await request.body()
        request_str = raw_body.decode("utf-8")
        log.info(f"request_str={request_str}")# 将字节转换为字符串
        request_json = json.loads(request_str)
    except:
        request_json = None
    try:
        request_args = dict(request.query_params)
    except:
        request_args = None

    resp_json = None
    response = None
    if is_forward:

        status_code, resp_json = AreaApManagerApis.v1_aapmgr_handler(request_method, sit_base_url, request_json,
                                                                     request_args)
        response = JSONResponse(content=resp_json, status_code=200, media_type='application/json')
    else:
        status_code = random.choice([500])
        match status_code:
            case 500:
                resp_json = {
                    "ret": {
                        "code": status_code,
                        "reason": f"{path}调用失败",
                        "msg": f"{path}调用失败",
                    }
                }
                response = JSONResponse(content=resp_json, status_code=status_code, media_type='application/json')
    log.error(f"response={resp_json}")
    handler_request_log(request, status_code, resp_json, modb_client, bool(request_json))
    return response


@cgvmagent_router.post("/{area_type}/{ip}:28668/v1/cgagent/game/endGame")
async def end_game(request: Request, area_type, ip):
    is_forward = True
    path = request.path_params
    request_method = request.method
    # 使用示例
    redis_value = redis_client.get_key("endGame")
    if redis_value:
        if redis_value.upper() == request_method:
            is_forward = False
    sit_base_url = "http://idc-202:40000" + f"/{area_type}/{ip}:28668/v1/cgagent/game/endGame"
    log.error(f"sit_base_url={sit_base_url}")
    try:
        raw_body = await request.body()
        request_str = raw_body.decode("utf-8")  # 将字节转换为字符串
        log.info(f"request_str={request_str}")  # 将字节转换为字符串
        request_json = json.loads(request_str)
    except:
        request_json = None
    try:
        request_args = dict(request.query_params)
    except:
        request_args = None

    resp_json = None
    response = None

    if is_forward:
        status_code, resp_json = AreaApManagerApis.v1_aapmgr_handler(request_method, sit_base_url, request_json,
                                                                     request_args)
        response = JSONResponse(content=resp_json, status_code=200, media_type='application/json')
    else:
        status_code = random.choice([500])
        match status_code:
            case 500:
                resp_json = {
                    "ret": {
                        "code": status_code,
                        "reason": f"{path}调用失败",
                        "msg": f"{path}调用失败",
                    }
                }
                response = JSONResponse(content=resp_json, status_code=status_code, media_type='application/json')
    log.error(f"response={resp_json}")
    handler_request_log(request, status_code, resp_json, modb_client, bool(request_json))
    return response
